package it.amicosmanettone.whatsimage.client;

import it.amicosmanettone.whatsimage.Configuration;
import it.amicosmanettone.whatsimage.MainActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class DownloadTask extends AsyncTask<Object,Object,Bitmap> {
	private ImageView _view;
	private Bitmap bmImg = null;

	public DownloadTask(ImageView imageView, String fileUrl) {
		Log.v("ImageDownloader", "Create new  DownloadTask for url "+fileUrl);
		this._view = imageView;
		this.execute(fileUrl);
	}

	@Override
	protected Bitmap doInBackground(Object... params) {
		URI myFileUrl = null;
		HttpGet getRequest = null;
		
		try {
			
			
			if(Configuration.IMAGE_MEMORY_CACHE_ACTIVE){
				if(MainActivity.mMemoryCache.get((String) params[0])!=null){
					 Log.v("CACHE","Immagine IN cache: "+(String) params[0]);
					return(MainActivity.mMemoryCache.get((String) params[0]));	
				}else{
					 Log.v("CACHE","Immagine NON IN cache: "+(String) params[0]);
				}
			}
			
			
			
			
			DefaultHttpClient client = new DefaultHttpClient();
			// forming a HttoGet request
			myFileUrl = new URI((String) params[0]);
			
			getRequest = new HttpGet(myFileUrl);
			HttpResponse response = client.execute(getRequest);
			// check 200 OK for success
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.v("ImageDownloader", "Error " + statusCode+ " while retrieving bitmap from " + myFileUrl);
				return null;
			}else{
				Log.v("ImageDownloader", "OK " + statusCode+ " while retrieving bitmap from " + myFileUrl);
			}//End if..else...
			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					// getting contents from the stream
					inputStream = entity.getContent();
					// decoding stream data back into image Bitmap that android
					// understands
					bmImg = BitmapFactory.decodeStream(inputStream);
					if(bmImg!=null){
						Log.v("ImageDownloader", "bmImg downloaded OK");
					}
					//_view.setImageBitmap(bmImg);
					if(Configuration.IMAGE_MEMORY_CACHE_ACTIVE){
				
							 MainActivity.mMemoryCache.put(myFileUrl.toString(), bmImg);
				
					}//End if...
					
					return(bmImg);
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}//End try...catch...finally..
			}else{
				Log.e("ImageDownloader", "Error entity null for "+myFileUrl);
			}//End if..else...
		} catch (Exception e) {
			// You Could provide a more explicit error message for IOException
			if(getRequest !=null ){
				getRequest.abort();
			}
			e.printStackTrace();
			Log.e("ImageDownloader", "Something went wrong while retrieving bitmap from " + myFileUrl + e.toString());
		}//End try...catch...
		return (null);
	}// End method...

	protected void onPostExecute(Bitmap image) {
		Log.v("ImageDownloader", "Sono in onPostExecute");
		_view.setImageBitmap(image);
	}// End method...

	

}// End class...
